// 处理标签自定义key value
export function tagsObjSwitch(obj) {
  var newObj = '';
  var arr = [];
  if (obj) {
    for (var i in obj) {
      newObj = {
        tagsId: i,
        tagsName: obj[i]
      };
      arr.push(newObj);
    }
  }
  return arr;
}

// 添加级联组合id
export function assignment(data) {
  var selectArr = [];
  var index = 0;
  var arrMap = (arr) => {
    arr.map(item => {
      if (item.sub && item.sub instanceof Array && item.sub.length > 0) {
        arrMap(item.sub);
      }
      selectArr.push(item.tagsId);
      item['selectArr'] = selectArr;
    });
  };
  data.map(item => {
    selectArr = [];
    selectArr.push(item.tagsId);
    if (item.sub && item.sub instanceof Array && item.sub.length > 0) {
      arrMap(item.sub);
    }
    item['selectArr'] = item.tagsId;
  });
  return data;
}

// 获取所有父节点
export function getParents(arr, id, key, children = 'sub') {
  for (var i in arr) {
    if (arr[i][key] === id) {
      return [arr[i][key]];
    } else {
      var items = getParents(arr[i][children], id, key, children);
      if (items !== undefined) {
        return items.concat(arr[i][key]);
      }
    }
  }
}

// 根据选中数组查找分类标签
export function getTagsItems(arr, option) {
  var newArr = [];
  var toArr = (tagsId, optArr) => {
    optArr.map(opt => {
      if (tagsId === opt.tagsId) {
        newArr.push(opt);
      } else {
        if (opt.sub !== undefined && opt.sub.length > 0) {
          toArr(tagsId, opt.sub);
        }
      }
    });
  };
  arr.map(item => {
    var itemStr = typeof item !== 'string' ? item[item.length - 1] : item;
    toArr(itemStr, option);
  });

  console.log('newArr:', newArr);
  return newArr;
}

// 数组降维去重
export function reduceArr(arr) {
  const newArr = [];
  for (var i in arr) {
    newArr.push(arr[i]);
  }
  const toArr = (arr) => {
    arr.forEach((item) => {
      item.sub instanceof Array ? toArr(item.sub) : newArr.push(item);
    });
  };
  toArr(arr);
  var newArr_ = newArr.filter(
    (self, index, newArr) => index === newArr.indexOf(self)
  );
  return newArr_;
}

// 组合接口数据
export function compose(arr, arrObj) {
  var str = '';
  var objStr = '';
  var _newArr = [];
  arr.map(item => {
    str = typeof item === 'object' ? item.join(',') : item;
    arrObj.map(objItem => {
      objStr = typeof objItem.selectArr === 'object' ? objItem.selectArr.join(',') : objItem.selectArr;
      if (str === objStr) {
        _newArr.push(objItem);
      }
    });
  });
  return _newArr;
}
